/*
 * @Author       : borfish
 * @Date         : 2025-08-07 16:39:55
 * @LastEditors  : borfish
 * @LastEditTime : 2025-08-12 11:18:15
 * @FilePath     : /src/upperMain.cpp
 * @Description  : 
 * Copyright 2025 OBKoro1, All Rights Reserved. 
 * 2025-08-07 16:39:55
 */
#include "include/upperMain.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QFormLayout>
#include <QMessageBox>
#include <QScrollBar>
#include <QDateTime>
#include <QFile>
#include <QApplication>
#include <QStyleFactory>
#include <QLinearGradient>
#include <QPalette>
#include <QProxyStyle>

upperMain::upperMain(QWidget* parent)
    : QMainWindow(parent)
{
    // 设置应用程序样式
    QApplication::setStyle(QStyleFactory::create("Fusion"));

    m_mqttHandler_ = new MQTTHandler(this);

    // 创建UI
    creatUI();

    // 应用样式
    applyStyles();

    // 设置信号连接
    setupConnections();

    // 初始状态
    updateUIState();
    onLogMessage("应用程序已启动");
}

upperMain::~upperMain()
{
    if(m_mqttHandler_->isConnected()) {
        m_mqttHandler_->disconnectFromBroker();
    }
}

void upperMain::creatUI() {
    // 设置窗口属性
    setWindowTitle("MQTT Client");
    setWindowIcon(QIcon(":/icons/logo.png"));
    setMinimumSize(900, 650);

    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setSpacing(10);
    mainLayout->setContentsMargins(15, 15, 15, 15);

    // 连接面板
    QGroupBox *connectionGroup = new QGroupBox("MQTT连接设置", this);
    QVBoxLayout *connLayout = new QVBoxLayout(connectionGroup);
    connLayout->setSpacing(10);

    // 第一行：地址和端口
    QHBoxLayout *row1 = new QHBoxLayout();
    row1->setSpacing(10);

    QLabel *hostLabel = new QLabel("代理地址:", this);
    m_hostEdit_ = new QLineEdit("broker.emqx.io", this);
    m_hostEdit_->setPlaceholderText("例如: broker.emqx.io");

    QLabel *portLabel = new QLabel("端口:", this);
    m_portEdit_ = new QLineEdit("1883", this);
    m_portEdit_->setMaximumWidth(80);


    QLabel *userLabel = new QLabel("用户名:", this);
    m_usernameEdit_ = new QLineEdit(this);
    m_usernameEdit_->setMaximumWidth(120);
    m_usernameEdit_->setPlaceholderText("可选");

    QLabel *passLabel = new QLabel("密码:", this);
    m_passwordEdit_ = new QLineEdit(this);
    m_passwordEdit_->setEchoMode(QLineEdit::Password);
    m_passwordEdit_->setMaximumWidth(120);
    m_passwordEdit_->setPlaceholderText("可选");

    row1->addWidget(hostLabel);
    row1->addWidget(m_hostEdit_, 2);
    row1->addWidget(portLabel);
    row1->addWidget(m_portEdit_);
    row1->addWidget(userLabel);
    row1->addWidget(m_usernameEdit_);
    row1->addWidget(passLabel);
    row1->addWidget(m_passwordEdit_);

    // 第二行：按钮和主题
    QHBoxLayout *row2 = new QHBoxLayout();
    row2->setSpacing(10);

    m_connectButton_ = new IconButton(":/icons/connect.svg", this);
    m_connectButton_->setToolTip("连接");

    m_disconnectButton_ = new IconButton(":/icons/disconnect.svg", this);
    m_disconnectButton_->setToolTip("断开");
    
    m_clearLogButton_ = new IconButton(":/icons/clear.svg", this);
    m_clearLogButton_->setToolTip("清除日志");
    
    QLabel *topicLabel = new QLabel("主题:", this);
    m_topicEdit_ = new QLineEdit("dt_mqtt/led", this);

    QLabel *qosLabel = new QLabel("QoS:", this);
    m_qosCombo_ = new QComboBox(this);
    m_qosCombo_->addItems({"0","1", "2"});
    m_qosCombo_->setMaximumWidth(60);

    row2->addWidget(m_connectButton_);
    row2->addWidget(m_disconnectButton_);
    row2->addWidget(m_clearLogButton_);
    row2->addStretch(1);
    row2->addWidget(topicLabel);
    row2->addWidget(m_topicEdit_, 2);
    row2->addWidget(qosLabel);
    row2->addWidget(m_qosCombo_);

    // 添加行到布局
    connLayout->addLayout(row1);
    connLayout->addLayout(row2);

    // 创建选项卡
    QTabWidget *tabWidget = new QTabWidget(this);
    tabWidget->setTabPosition(QTabWidget::West);
    tabWidget->tabBar()->setStyle(new QProxyStyle(tabWidget->tabBar()->style()));
    

    // 发布面板
    QWidget *publishPanel =  new QWidget(this);
    QVBoxLayout *publishLayout = new QVBoxLayout(publishPanel);
    publishLayout->setContentsMargins(15, 15, 15, 15);

    QGroupBox *pubGroup = new QGroupBox("发布消息", this);
    QFormLayout *pubForm = new QFormLayout(pubGroup);
    pubForm->setSpacing(15);

    m_pubTopicEdit_ = new QLineEdit("dt_mqtt/led", this);
    m_pubMessageEdit_ = new QLineEdit("ON", this);

    pubForm->addRow("主题:", m_pubTopicEdit_);
    pubForm->addRow("消息:", m_pubMessageEdit_);

    m_publishButton_ = new QPushButton("发布", this);
    m_publishButton_->setIcon(QIcon(":/icons/publish.svg"));
    m_publishButton_->setIconSize(QSize(24, 24));
    m_publishButton_->setFixedHeight(40);

    publishLayout->addWidget(pubGroup);
    publishLayout->addWidget(m_publishButton_, 0,Qt::AlignRight);
    publishLayout->addStretch(1);

    // 订阅面板
    QWidget *subscribePanel = new QWidget(this);
    QVBoxLayout *subscribeLayout = new QVBoxLayout(subscribePanel);
    subscribeLayout->setContentsMargins(15, 15, 15, 15);

    QGroupBox *subGroup = new QGroupBox("订阅设置", this);
    QFormLayout *subForm = new QFormLayout(subGroup);
    subForm->setSpacing(15);

    m_subTopicEdit_ = new QLineEdit("dt_mqtt/led", this);
    subForm->addRow("订阅主题:", m_subTopicEdit_);

    QHBoxLayout *subButtonLayout = new QHBoxLayout();
    m_subscribeButton_ = new QPushButton("订阅" , this);
    m_subscribeButton_->setIcon(QIcon(":/icons/subscribe.svg"));
    m_subscribeButton_->setIconSize(QSize(24, 24));
    m_subscribeButton_->setFixedHeight(40);

    m_unsubscribeButton_ = new QPushButton("取消订阅", this); 
    m_unsubscribeButton_->setIcon(QIcon(":/icons/unsubscribe.svg"));
    m_unsubscribeButton_->setIconSize(QSize(24, 24));
    m_unsubscribeButton_->setFixedHeight(40);

    subButtonLayout->addWidget(m_subscribeButton_);
    subButtonLayout->addWidget(m_unsubscribeButton_);
    subButtonLayout->addStretch(1);

    QGroupBox *messageGroup = new QGroupBox("接收消息", this);
    QVBoxLayout *messageLayout = new QVBoxLayout(messageGroup);
    m_subMessageDisplay_ = new QTextEdit(this);
    m_subMessageDisplay_->setReadOnly(true);
    m_subMessageDisplay_->setPlaceholderText("接收到的消息将显示在这里...");
    messageLayout->addWidget(m_subMessageDisplay_);

    subscribeLayout->addWidget(subGroup);
    subscribeLayout->addLayout(subButtonLayout);
    subscribeLayout->addWidget(messageGroup, 1);

    // 添加选项卡
    tabWidget->addTab(publishPanel, "发布");
    tabWidget->addTab(subscribePanel, "订阅");

    // 日志面板
    QGroupBox *logGroup = new QGroupBox("日志输出", this);
    QVBoxLayout *logLayout = new QVBoxLayout(logGroup);
    m_logDisplay_ = new QTextEdit(this);
    m_logDisplay_->setReadOnly(true);
    logLayout->addWidget(m_logDisplay_);

    // 状态栏
    m_statusBar_ = statusBar();
    m_statusLabel_ = new QLabel("未连接", this);
    m_messageCountLabel_ = new QLabel("消息: 0", this);
    m_errorCountLabel_ = new QLabel("错误: 0", this);

    QFont statusFont = m_statusLabel_->font();
    statusFont.setBold(true);
    m_statusLabel_->setFont(statusFont);

    m_statusBar_->addWidget(m_statusLabel_);
    m_statusBar_->addPermanentWidget(m_messageCountLabel_);
    m_statusBar_->addPermanentWidget(m_errorCountLabel_);

    // 主布局
    mainLayout->addWidget(connectionGroup);
    mainLayout->addWidget(tabWidget, 1);
    mainLayout->addWidget(logGroup);
    centralWidget->setLayout(mainLayout);
    setCentralWidget(centralWidget);

}

void upperMain::applyStyles()
{
    // 设置主窗口背景
    QLinearGradient gradient(0, 0, 0, height());
    gradient.setColorAt(0, QColor(240, 245, 249));
    gradient.setColorAt(1, QColor(220, 230, 240));

    QPalette palette;
    palette.setBrush(QPalette::Window, gradient);
    this->setPalette(palette);

    // 设置样式表
    QString styleSheet = R"(
    QGroupBox {
        border: 1px solid #c0d0e0;
        border-radius: 8px;
        margin-top: 1.5ex;
        padding: 10px;
        background-color: rgba(255, 255, 255, 220);
        font-weight: bold;
        color: #2c3e50;
    }
    
    QGroupBox::title {
        subcontrol-origin: margin;
        subcontrol-position: top center;
        padding: 0 5px;
        background-color: transparent;
    }
    
    QLineEdit, QTextEdit, QComboBox {
        border: 1px solid #c0d0e0;
        border-radius: 4px;
        padding: 5px;
        background: white;
        font-size: 14px;
    }
    
    QLineEdit:focus, QTextEdit:focus, QComboBox:focus {
        border: 1px solid #3498db;
    }
    
    QPushButton {
        border: none;
        border-radius: 4px;
        padding: 8px 16px;
        background-color: #3498db;
        color: white;
        font-weight: bold;
        min-width: 80px;
        font-size: 14px;
    }
    
    QPushButton:hover {
        background-color: #2980b9;
    }
    
    QPushButton:pressed {
        background-color: #1c6ea4;
    }
    
    QPushButton:disabled {
        background-color: #bdc3c7;
    }
    
    #connectButton {
        background-color: #2ecc71;
    }
    
    #connectButton:hover {
        background-color: #27ae60;
    }
    
    #disconnectButton {
        background-color: #e74c3c;
    }
    
    #disconnectButton:hover {
        background-color: #c0392b;
    }
    
    #publishButton {
        background-color: #e67e22;
    }
    
    #publishButton:hover {
        background-color: #d35400;
    }
    
    QStatusBar {
        background-color: #2c3e50;
        color: white;
        font-size: 12px;
    }
    
    QTextEdit {
        font-family: 'Consolas', 'Monaco', monospace;
        font-size: 12px;
    }
    
    QTabWidget::pane {
        border: none;
        background: transparent;
    }
    
    QTabBar::tab {
        background: #ecf0f1;
        border: 1px solid #bdc3c7;
        border-bottom: none;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;
        padding: 8px 16px;
        margin-right: 2px;
        font-weight: bold;
        color: #7f8c8d;
    }
    
    QTabBar::tab:selected {
        background: white;
        color: #3498db;
        border-color: #bdc3c7;
    }
    
    QTabBar::tab:hover {
        background: #d6dbdf;
    }
)";
    
    this->setStyleSheet(styleSheet);
}

void upperMain::setupConnections() {
    // UI按钮信号
    connect(m_connectButton_, &QPushButton::clicked, this, &upperMain::connectClicked);
    connect(m_disconnectButton_,&QPushButton::clicked, this, &upperMain::disconnectClicked);
    connect(m_publishButton_, &QPushButton::clicked, this, &upperMain::publishClicked);
    connect(m_subscribeButton_, &QPushButton::clicked, this, &upperMain::subscribeClicked);
    connect(m_unsubscribeButton_, &QPushButton::clicked, this, &upperMain::unsubscribeClicked);
    connect(m_clearLogButton_, &QPushButton::clicked, this, &upperMain::clearLog);
    // MQTT管理器信号
    connect(m_mqttHandler_, &MQTTHandler::connected, this, &upperMain::onMqttConnected);
    connect(m_mqttHandler_, &MQTTHandler::disconnected, this, &upperMain::onMqttDisconnected);
    connect(m_mqttHandler_, &MQTTHandler::connectionError, this, &upperMain::onMqttError);
    connect(m_mqttHandler_, &MQTTHandler::messageReceived, this, &upperMain::onMessageReceived);
    connect(m_mqttHandler_, &MQTTHandler::logMessage, this, &upperMain::onLogMessage);
}

void upperMain::updateUIState() {
    bool connected = m_mqttHandler_->isConnected();

    m_connectButton_->setEnabled(!connected);
    m_disconnectButton_->setEnabled(connected);
    m_publishButton_->setEnabled(connected);
    m_subscribeButton_->setEnabled(connected);


    QString status = connected ? "已连接" : "未连接";
    QString color = connected ? "color: #2ecc71;" : "color: #e74c3c;";
    m_statusLabel_->setText(QString("<span style='font-weight: bold; %1'>%2</span>").arg(color).arg(status));

    m_messageCountLabel_->setText(QString("消息: %1").arg(m_messageCount_));
    m_errorCountLabel_->setText(QString("错误: %1").arg(m_errorCount_));
}

void upperMain::connectClicked() {
    QString host = m_hostEdit_->text().trimmed();
    int port = m_portEdit_->text().toInt();
    QString username = m_usernameEdit_->text().trimmed();
    QString password = m_passwordEdit_->text().trimmed();
    
    m_mqttHandler_->connectToBroker(host, port, username, password);
}

void upperMain::disconnectClicked() {
    m_mqttHandler_->disconnectFromBroker();
} 

void upperMain::publishClicked() {
    QString topic = m_pubTopicEdit_->text().trimmed();
    QString message = m_pubMessageEdit_->text().trimmed();
    quint8 qos = static_cast<quint8>(m_qosCombo_->currentIndex());

    if(topic.isEmpty()) {
        QMessageBox::warning(this,"输入错误", "请输入发布主题");
        return;
    }
    if (message.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请输入消息内容");
        return;
    }
    m_mqttHandler_->publish(topic, message, qos);
}

void upperMain::subscribeClicked() {
    QString topic = m_subTopicEdit_->text().trimmed();
    quint8 qos = static_cast<quint8>(m_qosCombo_->currentIndex());

    if (topic.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请输入订阅主题");
        return;
    }

    m_mqttHandler_->subscribe(topic, qos);
    m_subscribeButton_->setEnabled(false);
    m_unsubscribeButton_->setEnabled(true);
}

void upperMain::unsubscribeClicked() {
    QString topic = m_subTopicEdit_->text().trimmed();
    if (topic.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请输入取消订阅主题");
        return;
    }

    m_mqttHandler_->unsubscribe(topic);
    m_subscribeButton_->setEnabled(true);
    m_unsubscribeButton_->setEnabled(false);
}

void upperMain::onMqttConnected() {
    updateUIState();
}

void upperMain::onMqttDisconnected() {
    updateUIState();
}

void upperMain::onMqttError(const QString &error) {
    QMessageBox::warning(this,"MQTT错误",error);
    m_errorCount_++;
    updateUIState();
}

void upperMain::onMessageReceived(const QString &topic, const QString &message) {
    QString time = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString html = QString("<div style='margin-bottom: 5px;'><b style='color: #3498db;'>[%1] %2:</b> %3</div>")
                    .arg(time).arg(topic).arg(message);

    m_subMessageDisplay_->append(html);
    m_messageCount_++;
    updateUIState();
}

void upperMain::onLogMessage(const QString &message) {
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString level = "INFO";
    QString color = "#3498db";

    if (message.contains("错误", Qt::CaseInsensitive)) {
        level = "ERROR";
        color = "#e74c3c";
    }
    else if (message.contains("警告", Qt::CaseInsensitive)) {
        level = "WARN";
        color = "#f39c12";
    }

    QString html = QString("<div style='margin-bottom: 2px;'>"
                           "<span style='color: #95a5a6;'>%1</span> "
                           "<span style='color: %2; font-weight: bold;'>[%3]</span> "
                           "<span>%4</span></div>")
                   .arg(timestamp).arg(color).arg(level).arg(message);

    m_logDisplay_->append(html);

    QScrollBar *scrollbar = m_logDisplay_->verticalScrollBar();
    scrollbar->setValue(scrollbar->maximum());
}

void upperMain::clearLog() {
    m_logDisplay_->clear();
    onLogMessage("日志已清除");
}